package top.codedance.iotp.server.net.initializer;

import top.codedance.iotp.server.net.handle.WsChannelAuthHandler;
import top.codedance.iotp.server.net.handle.WsChannelHandler;
import top.codedance.iotp.server.net.handle.WsCounterHandler;
import cd.io.netty.channel.ChannelHandlerContext;
import cd.io.netty.channel.ChannelInitializer;
import cd.io.netty.channel.socket.SocketChannel;
import cd.io.netty.handler.codec.http.HttpObjectAggregator;
import cd.io.netty.handler.codec.http.HttpServerCodec;
import cd.io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import cd.io.netty.handler.stream.ChunkedWriteHandler;

public class WsPipelineInitializer extends ChannelInitializer<SocketChannel> {

    protected void initChannel(SocketChannel socketChannel) throws Exception {
        socketChannel.pipeline()
                .addLast(new HttpServerCodec())
                .addLast("http-chunked", new ChunkedWriteHandler())
                .addLast("httpAggregator", new HttpObjectAggregator(65535))
                .addLast(new WsChannelAuthHandler())
                .addLast(new WebSocketServerProtocolHandler("/services",null,true,65535))
                .addLast(new WsChannelHandler(socketChannel))
                .addLast(new WsCounterHandler());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ctx.close();
        super.channelInactive(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        ctx.close();
        super.channelUnregistered(ctx);
    }
}
